//
//  UIAsyncImageView.swift
//  viewcontroller_test
//
//  Created by 潘茹燕 on 16/4/2.
//  Copyright © 2016年 海南开工信息技术有限公司. All rights reserved.
//

import UIKit

class UIAsyncImageView: UIImageView {

    
    private var connection: NSURLConnection?
    
    init() {
        super.init(frame: CGRectZero)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    
    func LoadImageFromURL(urlString: String) {
        
        if connection != nil {
            connection?.cancel()
            connection = nil
        }
        
        //let request = NSURLRequest(URL: NSURL(fileURLWithPath: urlString), cachePolicy: NSURLRequestCachePolicy.UseProtocolCachePolicy, timeoutInterval: 60.0)
        
        
        let indicatorView = UIActivityIndicatorView(frame: CGRect(x:  frame.midX - 40, y: frame.midY - 40, width: 80, height: 80))
        
        indicatorView.color = UIColor.blackColor()
        indicatorView.startAnimating()
        addSubview(indicatorView)
        
        
        let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
        
        let task = session.dataTaskWithURL(NSURL(string: urlString)!) { (data, response, error) in
            
            
            session.finishTasksAndInvalidate()
            
            if error == nil && data != nil {
                
                
                // 如果获取的是html文本内容
                // let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
                
                if let image = UIImage(data: data!) {
                    
                    dispatch_async(dispatch_get_main_queue(), { 
                        self.image = image
                    })
                    
                    
                }
                
            }
            else {
                
                NSLog("\(error)")
            }
            
            dispatch_async(dispatch_get_main_queue(), { 
                indicatorView.stopAnimating()
                indicatorView.removeFromSuperview()
            })
            
            
            
        }
        
        task.resume()
        
    }
    
    
    

}
